package demo2;

import java.util.*;

public class Solution {

    public int maximumWhiteTiles(int[][] tiles, int carpetLen) {
        Arrays.sort(tiles, (t1, t2) -> t1[0] - t2[0]);
        int n = tiles.length, l = 0, r = 0, sum = 0, max = 0;

        while(l <= r && r < n){
            int left = tiles[l][0], right = left + carpetLen - 1;
            if(right > tiles[r][1]){
                sum += tiles[r][1] - tiles[r][0] + 1;
                r++;
                max = Math.max(max, sum);
            }else{
                if(right >= tiles[r][0]){
                    max = Math.max(max, sum + right - tiles[r][0] + 1);
                }
                sum -= tiles[l][1] - tiles[l][0] + 1;
                l++;
            }
        }
        return max;
    }

    public int longestEqualSubarray(List<Integer> nums, int k) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.size(); i++) {
            map.computeIfAbsent(nums.get(i), x -> new ArrayList<>()).add(i);
        }

        int ret = 0;
        for(List<Integer> list : map.values()){
            for(int i = 0, j = 0; i < list.size(); i++){
                while(list.get(i) - list.get(j) - (i - j) > k){
                    j++;
                }
                ret = Math.max(ret, i - j + 1);
            }
        }
        return ret;
    }
}
